package com.example.administrator.liveapp.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.activity.OrderDetails;
import com.example.administrator.liveapp.bean.AllOrdersBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.TimeChangeUtil;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/27 0027.
 */

public class AllOrdersBookRecyclerAdapter extends RecyclerView.Adapter<AllOrdersBookRecyclerAdapter.ViewHolder> implements View.OnClickListener{

    public List<AllOrdersBean.BookOrderBean> bookOrder;
    public Context context;
    public AllordersBookList ab;

    //支付
    private PopupWindow mPopWindow;
    private Button payButton;
    private ImageView zhifubao;
    private ImageView weixin;
    private IWXAPI mIwxapi;
    private TextView moneys;
    private LinearLayout booking_layout;


    public AllOrdersBookRecyclerAdapter(List<AllOrdersBean.BookOrderBean> bookOrder) {
        this.bookOrder = bookOrder;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.allorders_store_item, null);
        ViewHolder viewHolder = new ViewHolder(view);
        context = parent.getContext();
        //将创建的View注册点击事件
        view.setOnClickListener(this);
        return viewHolder;
    }

    int positions;
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
//        holder.store_name.setText(bookOrder.get(position).getName());
        if (bookOrder.get(position).getBookOrderStatus().equals("0")) {
            holder.payments_status.setText("支付状态：待支付");
//            holder.payment_time.setText("请于" + TimeChangeUtil.getStrTime(bookOrder.get(position).getTimeForPay() + "") + "前完成支付");
//            holder.Immediate_payment_button.setVisibility(View.VISIBLE);
            holder.payment_time.setVisibility(View.VISIBLE);
        } else if (bookOrder.get(position).getBookOrderStatus().equals("1")) {
            holder.payments_status.setText("支付状态：已支付");
//            holder.Immediate_payment_button.setVisibility(View.GONE);
//            holder.payment_time.setVisibility(View.GONE);
        }else if(bookOrder.get(position).getBookOrderStatus().equals("2")){
            holder.payments_status.setText("支付状态：交易取消");
//            holder.Immediate_payment_button.setVisibility(View.GONE);
//            holder.payment_time.setVisibility(View.GONE);
        }else if(bookOrder.get(position).getBookOrderStatus().equals("3")){
            holder.payments_status.setText("支付状态：已退款");
//            holder.Immediate_payment_button.setVisibility(View.GONE);
//            holder.payment_time.setVisibility(View.GONE);
        }else if(bookOrder.get(position).getBookOrderStatus().equals("4")){
            holder.payments_status.setText("支付状态：退款中");
//            holder.Immediate_payment_button.setVisibility(View.GONE);
//            holder.payment_time.setVisibility(View.GONE);
        }
        holder.Immediate_payment_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPay(position);
//                showPopupWindow();
//                positions = position;
            }
        });
        holder.order_number.setText("订单号："+bookOrder.get(position).getGoodsOrder());
        FullyLinearLayoutManager mLinearLayoutManager = new FullyLinearLayoutManager(context);
        mLinearLayoutManager.setScrollEnabled(false);
        holder.allorders_book_item.setLayoutManager(mLinearLayoutManager);
        holder.allorders_book_item.setHasFixedSize(true);
        ab = new AllordersBookList(bookOrder.get(position).getBookList());
        holder.allorders_book_item.setAdapter(ab);
        //将position保存在itemView的Tag中，以便点击时进行获取
        holder.itemView.setTag(position);
    }


//    private void showPopupWindow() {
//        //设置contentView
//        View contentView = LayoutInflater.from(context).inflate(R.layout.appointment_pay_popwindow_page, null);
//        mPopWindow = new PopupWindow(contentView,
//                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
//        mPopWindow.setContentView(contentView);
//        Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.trans, null);
//        mPopWindow.setBackgroundDrawable(drawable);
//        mPopWindow.setOutsideTouchable(true);
//        payButton = (Button) contentView.findViewById(R.id.pay_button);
//        zhifubao = (ImageView) contentView.findViewById(R.id.zhifubao);
//        weixin = (ImageView) contentView.findViewById(R.id.weixin);
//        moneys = (TextView) contentView.findViewById(R.id.money);
//        moneys.setText("");
//        zhifubao.setOnClickListener(this);
//        weixin.setOnClickListener(this);
//        payButton.setOnClickListener(this);
//        //设置各个控件的点击响应
//
//        //显示PopupWindow
//        View rootview = LayoutInflater.from(context).inflate(R.layout.booking_detailspage, null);
//        showPopmenu(rootview);
//    }

//    private void showPopmenu(View rootview) {
//        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                WindowManager.LayoutParams lp = window.getAttributes();
//                lp.alpha = 1f;
//                window.setAttributes(lp);
//            }
//        });
//        // 显示窗口位置
//        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//        // 设置layout在PopupWindow中显示的位置
//        WindowManager.LayoutParams lp = window.getAttributes();
//        lp.alpha = 0.4f;
//        window.setAttributes(lp);
//    }

    /**
     * 微信支付
     * @param position
     */
    private void requestPay(int position) {
        String url = AppUrl.URL + AppUrl.payUrl;
        Map<String,String> map = new HashMap<>();
        map.put("body","半书房大学");
        map.put("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
        map.put("goodsOrder",bookOrder.get(position).getGoodsOrder());
        // 微信
        XUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                JSONObject obj = null;
                try {
                    obj = new JSONObject(result);
                    // 微信支付回调
                    setWeChat(obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast.makeText(context, ex.getMessage()+"1", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });
    }

    /**
     * 微信支付
     */
    private void setWeChat(JSONObject obj) {
        mIwxapi = WXAPIFactory.createWXAPI(context, obj.optString("appid"));
        mIwxapi.registerApp(obj.optString("appid"));// 将应用注册到微信
        if (mIwxapi != null && mIwxapi.isWXAppInstalled()) {// 判断用户有没有安装微信
            PayReq req = new PayReq();
            req.appId = obj.optString("appid");
            req.partnerId = obj.optString("partnerid");
            req.prepayId = obj.optString("prepayid");
            req.nonceStr = obj.optString("noncestr");
            req.timeStamp = obj.optString("timestamp");
            req.packageValue = obj.optString("package");
            req.sign = obj.optString("sign");
            // req.extData = "app data";// 可选
            mIwxapi.sendReq(req);
        } else {
            Toast.makeText(context, "用户未安装微信", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    @Override
    public int getItemCount() {
        if (bookOrder != null) {
            return bookOrder.size();
        } else {
            return 0;
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public RecyclerView allorders_book_item;
        public TextView store_name;
        public TextView payments_status;
        public TextView payment_time;//待支付时间
        private Button Immediate_payment_button;//支付按钮
        private TextView order_number;

        public ViewHolder(View itemView) {
            super(itemView);
            store_name = (TextView) itemView.findViewById(R.id.store_name);
            allorders_book_item = (RecyclerView) itemView.findViewById(R.id.allorders_book_item);
            payments_status = (TextView) itemView.findViewById(R.id.payments_status);
            payment_time = (TextView) itemView.findViewById(R.id.payment_time);
            Immediate_payment_button = (Button) itemView.findViewById(R.id.Immediate_payment_button);
            order_number = (TextView) itemView.findViewById(R.id.order_number);
        }
    }

    public void onClick(View v) {
        switch (v.getId()){
//            case R.id.pay_button://确认支付
//                requestPay();
//                break;
//            case R.id.zhifubao:
//                zhifubao.setImageResource(R.drawable.check);
//                weixin.setImageResource(R.drawable.no_check);
//                break;
//            case R.id.weixin:
//                weixin.setImageResource(R.drawable.check);
//                zhifubao.setImageResource(R.drawable.no_check);
//                break;
        }
        if (mOnItemClickListener != null) {
            //注意这里使用getTag方法获取position
            mOnItemClickListener.onItemClick(v, (int) v.getTag());
        }
    }

    private AllOrdersBookRecyclerAdapter.OnItemClickListener mOnItemClickListener = null;

    //define interface
    public static interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public void setOnItemClickListener(AllOrdersBookRecyclerAdapter.OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }



    class AllordersBookList extends RecyclerView.Adapter<AllordersBookList.ViewHolder> {
        public Context context;
        public List<AllOrdersBean.BookOrderBean.BookListBean> bookList;

        public AllordersBookList(List<AllOrdersBean.BookOrderBean.BookListBean> bookList) {
            this.bookList = bookList;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.allorders_book_item, null);
            ViewHolder viewHolder = new ViewHolder(view);
            context = parent.getContext();
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Glide.with(context)
                    .load(AppUrl.URL + bookList.get(position).getBookBannerImg().substring(1, bookList.get(position).getBookBannerImg().indexOf("|")))
                    .into(holder.AllOrders_book_image);
            holder.AllOrders_book_name.setText(bookList.get(position).getBookTitle());
            holder.AllOrders_money.setText("¥ " + bookList.get(position).getPrice());
            holder.AllOrders_book_number.setText("x" + bookList.get(position).getNum());
        }


        @Override
        public int getItemCount() {
            if (bookList != null) {
                return bookList.size();
            } else {
                return 0;
            }

        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView AllOrders_book_image;//图片
            public TextView AllOrders_book_name;//名称
            public TextView AllOrders_money;//单价
            public TextView AllOrders_book_number;//数量

            public ViewHolder(View itemView) {
                super(itemView);
                AllOrders_book_image = (ImageView) itemView.findViewById(R.id.AllOrders_book_image);
                AllOrders_book_name = (TextView) itemView.findViewById(R.id.AllOrders_book_name);
                AllOrders_money = (TextView) itemView.findViewById(R.id.AllOrders_money);
                AllOrders_book_number = (TextView) itemView.findViewById(R.id.AllOrders_book_number);
            }
        }
    }

}
